// 用户状态管理

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { User } from '@/types/user';
import { TokenManager, UserStorage } from '@/utils/storage';

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(TokenManager.getToken());
  const userInfo = ref<User | null>(UserStorage.getUser());

  // 计算属性
  const isLoggedIn = computed(() => !!token.value);

  // 动作
  const setToken = (newToken: string) => {
    token.value = newToken;
    TokenManager.setToken(newToken);
  };

  const setUserInfo = (user: User) => {
    userInfo.value = user;
    UserStorage.setUser(user);
  };

  const login = (newToken: string, user: User) => {
    setToken(newToken);
    setUserInfo(user);
  };

  const logout = () => {
    token.value = null;
    userInfo.value = null;
    TokenManager.removeToken();
    UserStorage.removeUser();
  };

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    setUserInfo,
    login,
    logout
  };
});